// src/main/java/com/mcp_life/mcp_life/common/jwt/JwtInterceptor.java
package com.mcp_life.common.jwt;

import com.mcp_life.common.context.UserContextHolder;
import com.mcp_life.entity.pojo.User;
import com.mcp_life.module.userbasemodules.mapper.UserMapper;
import com.mcp_life.module.userbasemodules.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        // 记录请求信息
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        String remoteAddr = request.getRemoteAddr();
        String authorizationHeader = request.getHeader("Authorization");

        log.info("拦截到请求: {} {} 来自: {}", method, requestURI, remoteAddr);

        // 允许登录和注册接口不进行JWT验证
        if (requestURI.contains("/auth/login") || requestURI.contains("/auth/register")) {
            log.info("放行认证接口: {} {}", method, requestURI);
            return true;
        }

        log.info("开始JWT验证: {} {}", method, requestURI);

        // 从请求头中获取token
        String token = request.getHeader("Authorization");
        log.info("token: {}", token);

        if (token != null ) {
            //token = token.substring(7);
           // log.info("提取到token: {}", token.substring(0, Math.min(token.length(), 10)) + "...");

            try {
                // 验证token并获取用户名
                String account = jwtUtil.extractUsername(token);
                log.info("从token中提取用户名: {}", account);

                if (account != null && jwtUtil.validateToken(token, account)) {
                    // 查询用户ID
                    User user = userMapper.findByAccount(account);
                    if (user != null) {
                        log.info("用户：{}", user);
                        // 将用户ID存储到ThreadLocal中
                        UserContextHolder.setUserId(user.getUserId());
                        log.info("用户验证成功: {}, 用户ID: {}", account, user.getUserId());

                        // 可以将用户信息存储到request中供后续使用
                        request.setAttribute("username", account);
                        return true;
                    } else {
                        log.warn("用户不存在: {}", account);
                    }
                } else {
                    log.warn("token验证失败: {}", account);
                }
            } catch (Exception e) {
                log.error("token解析异常: ", e);
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().write("{\"error\":\"Invalid token\"}");
                return false;
            }
        } else {
            log.warn("缺少有效的Authorization头或格式不正确");
        }

        log.info("用户验证失败，返回401");

        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getWriter().write("{\"error\":\"Access denied. No valid token provided.\"}");
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求完成后清除ThreadLocal中的数据
        UserContextHolder.remove();
        log.info("请求完成，清理ThreadLocal数据");
    }
}
